<template>
  <div class="push-method-manage-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">推送方式管理</h1>
        <p class="page-desc">管理APP推送方式类型和演示图片</p>
      </div>
      <div class="header-right">
        <el-button type="primary" size="large" @click="openAddDialog">
          <el-icon><Plus /></el-icon>
          新增推送方式
        </el-button>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <el-card class="main-content" shadow="never">
      <!-- 推送方式列表 -->
      <div class="method-list">
        <el-row :gutter="20">
          <el-col :span="8" v-for="method in pushMethods" :key="method.id">
            <el-card class="method-card" shadow="hover">
              <div class="method-header">
                <div class="method-info">
                  <h3 class="method-name">{{ method.name }}</h3>
                  <p class="method-desc">{{ method.description }}</p>
                </div>
                <div class="method-actions">
                  <el-button size="small" @click="openEditDialog(method)">
                    <el-icon><Edit /></el-icon>
                    编辑
                  </el-button>
                  <el-button size="small" type="danger" @click="deleteMethod(method)">
                    <el-icon><Delete /></el-icon>
                    删除
                  </el-button>
                </div>
              </div>
              
              <div class="method-preview">
                <div class="preview-title">演示效果</div>
                <div class="preview-image">
                  <img v-if="method.demoImage" :src="method.demoImage" :alt="method.name" />
                  <div v-else class="no-image">
                    <el-icon><Picture /></el-icon>
                    <span>暂无演示图</span>
                  </div>
                </div>
              </div>
              
              <div class="method-details">
                <div class="detail-item">
                  <span class="label">推送位置：</span>
                  <el-tag :type="getPositionTagType(method.position)" size="small">
                    {{ getPositionText(method.position) }}
                  </el-tag>
                </div>
                <div class="detail-item">
                  <span class="label">状态：</span>
                  <el-tag :type="method.enabled ? 'success' : 'info'" size="small">
                    {{ method.enabled ? '启用' : '禁用' }}
                  </el-tag>
                </div>
                <div class="detail-item">
                  <span class="label">创建时间：</span>
                  <span class="value">{{ method.createdAt }}</span>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogMode === 'add' ? '新增推送方式' : '编辑推送方式'" 
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="dialogForm" label-width="120px" :rules="dialogRules" ref="dialogFormRef">
        <el-form-item label="推送方式名称" prop="name">
          <el-input v-model="dialogForm.name" placeholder="请输入推送方式名称" />
        </el-form-item>
        
        <el-form-item label="推送方式描述" prop="description">
          <el-input 
            v-model="dialogForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入推送方式描述"
          />
        </el-form-item>
        
        <el-form-item label="推送位置" prop="position">
          <el-select v-model="dialogForm.position" placeholder="请选择推送位置" style="width: 100%">
            <el-option label="手机外部通知" value="outside" />
            <el-option label="APP顶部横幅" value="top" />
            <el-option label="图标角标" value="icon" />
            <el-option label="弹窗提醒" value="popup" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="演示图片" prop="demoImage">
          <el-upload
            class="demo-uploader"
            action="#"
            :show-file-list="false"
            :auto-upload="false"
            :on-change="handleImageChange"
            accept="image/*"
          >
            <img v-if="dialogForm.demoImage" :src="dialogForm.demoImage" class="demo-image" />
            <el-icon v-else class="demo-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">建议上传 400x600 像素的图片，支持 jpg、png 格式</div>
        </el-form-item>
        
        <el-form-item label="启用状态">
          <el-switch v-model="dialogForm.enabled" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitDialog" :loading="saving">
          {{ dialogMode === 'add' ? '创建' : '保存' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox, ElForm } from 'element-plus'
import { Plus, Edit, Delete, Picture } from '@element-plus/icons-vue'

interface PushMethod {
  id: number
  name: string
  description: string
  position: 'outside' | 'top' | 'icon' | 'popup'
  demoImage: string
  enabled: boolean
  createdAt: string
  updatedAt: string
}

// Mock 数据
const pushMethods = ref<PushMethod[]>([
  {
    id: 1,
    name: '系统推送通知',
    description: '手机锁屏状态下的系统级Push通知，到达率高，用户感知强',
    position: 'outside',
    demoImage: '/demo/push-notification-demo.png',
    enabled: true,
    createdAt: '2024-07-18 10:00:00',
    updatedAt: '2024-07-18 10:00:00'
  },
  {
    id: 2,
    name: 'APP内顶部消息',
    description: '在APP顶部显示横幅消息，用户体验友好，不打断用户操作',
    position: 'top',
    demoImage: '/demo/app-top-demo.png',
    enabled: true,
    createdAt: '2024-07-17 14:30:00',
    updatedAt: '2024-07-17 14:30:00'
  },
  {
    id: 3,
    name: '红点消息',
    description: '在图标上显示红点角标，提醒用户查看，轻量级提醒方式',
    position: 'icon',
    demoImage: '/demo/red-dot-demo.png',
    enabled: true,
    createdAt: '2024-07-16 09:15:00',
    updatedAt: '2024-07-16 09:15:00'
  }
])

// 对话框相关
const dialogVisible = ref(false)
const dialogMode = ref<'add' | 'edit'>('add')
const saving = ref(false)

const dialogForm = reactive({
  id: 0,
  name: '',
  description: '',
  position: 'outside' as 'outside' | 'top' | 'icon' | 'popup',
  demoImage: '',
  enabled: true
})

const dialogFormRef = ref<InstanceType<typeof ElForm> | null>(null)

const dialogRules = {
  name: [{ required: true, message: '请输入推送方式名称', trigger: 'blur' }],
  description: [{ required: true, message: '请输入推送方式描述', trigger: 'blur' }],
  position: [{ required: true, message: '请选择推送位置', trigger: 'change' }]
}

// 工具函数
function getPositionTagType(position: string): string {
  const typeMap: Record<string, string> = {
    'outside': 'success',
    'top': 'primary',
    'icon': 'danger',
    'popup': 'warning'
  }
  return typeMap[position] || 'info'
}

function getPositionText(position: string): string {
  const textMap: Record<string, string> = {
    'outside': '手机外部',
    'top': 'APP顶部',
    'icon': '图标角标',
    'popup': '弹窗提醒'
  }
  return textMap[position] || '未知'
}

// 对话框操作
function openAddDialog() {
  dialogMode.value = 'add'
  Object.assign(dialogForm, {
    id: 0,
    name: '',
    description: '',
    position: 'outside',
    demoImage: '',
    enabled: true
  })
  dialogVisible.value = true
}

function openEditDialog(method: PushMethod) {
  dialogMode.value = 'edit'
  Object.assign(dialogForm, method)
  dialogVisible.value = true
}

function submitDialog() {
  (dialogFormRef.value as any).validate(async (valid: boolean) => {
    if (!valid) return
    
    saving.value = true
    
    try {
      if (dialogMode.value === 'add') {
        const now = new Date().toLocaleString('zh-CN', { hour12: false })
        const newMethod: PushMethod = {
          id: Date.now(),
          name: dialogForm.name,
          description: dialogForm.description,
          position: dialogForm.position,
          demoImage: dialogForm.demoImage,
          enabled: dialogForm.enabled,
          createdAt: now,
          updatedAt: now
        }
        pushMethods.value.unshift(newMethod)
        ElMessage.success('推送方式创建成功')
      } else {
        const idx = pushMethods.value.findIndex(item => item.id === dialogForm.id)
        if (idx > -1) {
          pushMethods.value[idx] = {
            ...dialogForm,
            createdAt: pushMethods.value[idx].createdAt,
            updatedAt: new Date().toLocaleString('zh-CN', { hour12: false })
          } as PushMethod
          ElMessage.success('推送方式修改成功')
        }
      }
      dialogVisible.value = false
    } catch (error) {
      ElMessage.error('操作失败，请重试')
    } finally {
      saving.value = false
    }
  })
}

function deleteMethod(method: PushMethod) {
  ElMessageBox.confirm(
    `确定要删除推送方式"${method.name}"吗？删除后无法恢复。`,
    '确认删除',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    pushMethods.value = pushMethods.value.filter(item => item.id !== method.id)
    ElMessage.success('删除成功')
  }).catch(() => {
    // 用户取消删除
  })
}

function handleImageChange(file: any) {
  const reader = new FileReader()
  reader.onload = (e) => {
    dialogForm.demoImage = e.target?.result as string
  }
  reader.readAsDataURL(file.raw)
}
</script>

<style scoped>
.push-method-manage-page {
  width: 100%;
  min-height: 100vh;
  background: #f5f7fa;
  padding: 0;
  margin: 0;
}

/* 页面头部 */
.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 32px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.header-left .page-title {
  font-size: 28px;
  font-weight: 700;
  margin: 0 0 8px 0;
  text-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.header-left .page-desc {
  font-size: 16px;
  opacity: 0.9;
  margin: 0;
}

.header-right .el-button {
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

/* 主要内容区域 */
.main-content {
  margin: 0 24px 24px 24px;
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0,0,0,0.08);
  padding: 24px;
}

.method-list {
  width: 100%;
}

.method-card {
  border: none;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.08);
  transition: all 0.3s ease;
  margin-bottom: 20px;
}

.method-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(0,0,0,0.15);
}

.method-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.method-info {
  flex: 1;
}

.method-name {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 8px 0;
}

.method-desc {
  font-size: 14px;
  color: #7f8c8d;
  margin: 0;
  line-height: 1.5;
}

.method-actions {
  display: flex;
  gap: 8px;
}

.method-preview {
  margin-bottom: 16px;
}

.preview-title {
  font-size: 14px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 12px;
}

.preview-image {
  width: 100%;
  height: 200px;
  border-radius: 8px;
  overflow: hidden;
  background: #f8f9fa;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px dashed #e9ecef;
}

.preview-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.no-image {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  color: #95a5a6;
}

.no-image .el-icon {
  font-size: 32px;
}

.method-details {
  border-top: 1px solid #f0f0f0;
  padding-top: 16px;
}

.detail-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.detail-item:last-child {
  margin-bottom: 0;
}

.label {
  font-size: 14px;
  color: #666;
  margin-right: 8px;
  min-width: 80px;
}

.value {
  font-size: 14px;
  color: #2c3e50;
}

/* 上传组件样式 */
.demo-uploader {
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  width: 200px;
  height: 120px;
  text-align: center;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.demo-uploader:hover {
  border-color: #409eff;
}

.demo-image {
  width: 200px;
  height: 120px;
  display: block;
  object-fit: cover;
}

.demo-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
  line-height: 1.4;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .method-list .el-col {
    margin-bottom: 20px;
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    text-align: center;
    gap: 16px;
  }

  .main-content {
    margin: 0 12px 24px 12px;
    padding: 16px;
  }

  .method-header {
    flex-direction: column;
    gap: 12px;
  }

  .method-actions {
    align-self: stretch;
  }
}
</style>
